using Game.Component.Character;
using Game.Core;
using Game.Main.Model;
using Game.Manager;
using Game.XH;
using SimpleJSON;
using UnityEngine;

namespace Game.Component
{
	public class BeverageItem : BaseItem
	{
		private SpriteRenderer waterSprite;

		private float fillAmount;

		private ItemComponentTrigger targetItem;

		private bool isDrinking;

		public override void Init(ItemArchiveData data)
		{
			base.Init(data);
			Transform transform = model.Find("WaterFill");
			if (transform != null)
			{
				transform.SetLocalZ(1E-05f);
				waterSprite = transform.GetComponent<SpriteRenderer>();
				float num = waterSprite.sprite.texture.height;
				Rect textureRect = waterSprite.sprite.textureRect;
				float num2 = textureRect.yMin / num;
				float value = textureRect.yMax / num - num2;
				waterSprite.material.SetFloat("_StartY", num2);
				waterSprite.material.SetFloat("_TotalY", value);
			}
			SetFillAmount(data.floatParam1 + 1f);
		}

		protected override void LateUpdate()
		{
			base.LateUpdate();
			if (isDrinking)
			{
				MinusFill(Time.deltaTime / 2f);
				if (fillAmount <= 0f)
				{
					RecoverNormal();
					RemoveAudioPlayer();
				}
			}
		}

		public void MinusFill(float val)
		{
			if (fillAmount > 0f)
			{
				fillAmount -= val;
				if (fillAmount <= 0f)
				{
					fillAmount = 0f;
				}
				SetFillAmount(fillAmount);
			}
		}

		protected override void OnItemCompTriggerEnter(ColliderData collData)
		{
			base.OnItemCompTriggerEnter(collData);
			if (!(fillAmount <= 0f) && collData.trigger.type == ItemComponentTrigger.Type.Mouth && typeof(CharacterItem).IsAssignableFrom(collData.item.GetType()))
			{
				isDrinking = true;
				if (targetItem != null)
				{
					((CharacterItem)targetItem.owner).SetMouthState(Face.MouthState.Normal);
					targetItem = null;
				}
				targetItem = collData.trigger;
				((CharacterItem)targetItem.owner).SetMouthState(Face.MouthState.Open);
				RotateToAngle(30f);
				Singleton<AudioManager>.Instance.PlayAudio("sound_drinking", true, GetAudioPlayer());
			}
		}

		protected override void OnItemCompTriggerExit(ColliderData collData)
		{
			base.OnItemCompTriggerExit(collData);
			if (collData.trigger == targetItem)
			{
				RecoverNormal();
			}
		}

		public override void TouchUp(TouchEventData touchEventData)
		{
			base.TouchUp(touchEventData);
			RecoverNormal();
		}

		private void SetFillAmount(float val)
		{
			fillAmount = val;
			if (waterSprite != null)
			{
				waterSprite.material.SetFloat("_Fill", fillAmount);
			}
		}

		private void RecoverNormal()
		{
			isDrinking = false;
			if (targetItem != null)
			{
				if (typeof(CharacterItem).IsAssignableFrom(targetItem.owner.GetType()))
				{
					((CharacterItem)targetItem.owner).SetMouthState(Face.MouthState.Normal);
					RotateToAngle(0f);
				}
				targetItem = null;
				RemoveAudioPlayer();
			}
		}

		public override void PackData(JSONObject obj)
		{
			base.PackData(obj);
			obj["62"] = fillAmount - 1f;
		}
	}
}
